import { $event } from '../../../utils'
import { GlobalData } from '../../../store/state'
import { activityApi } from '../../../api/activity'

Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    noMore: false,
    navData: [] as NavData[],
    currentTab: 0,
    navScrollLeft: 0,
    list: [[] as Activity[]] as any[],
    currentTabList: [] as number[],
    city: '',
    /** 想加入锁 */
    wantJoin: false,
    canPublish: false,
  },
  async onLoad() {
    this.getCity()
    await this.getClassify()
    this.onReset()
    $event.on('after:boot', this, () => {
      this.setData({ navigationHeight: GlobalData.navigationHeight })
    })
    $event.on('activityChange', this, () => {
      this.onReset()
    })
    $event.on('after:changeCity', this, () => {
      this.getCity()
      this.onReset()
    })
    const abilities = GlobalData.userAbilities
    this.setData({
      canPublish: abilities && abilities.some((v: any) => v.name === 'event:create'),
    })
  },
  async onShow() {
    this.setData({ navigationHeight: GlobalData.navigationHeight })
  },
  /** 获取地址 */
  getCity() {
    const city = wx.getStorageSync('activityCity')
    this.setData({
      city,
    })
  },
  switchNav(event: WechatMiniprogram.CustomEvent) {
    const windowWidth = GlobalData.clientWidth
    const cur = event.currentTarget.dataset.current
    //每个tab选项宽度占1/5
    const singleNavWidth = windowWidth / 5
    //tab选项居中
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth,
    })
    if (this.data.currentTab == cur) {
      return
    } else {
      this.setData({
        currentTab: cur,
      })
      this.switchList()
    }
  },
  switchList() {
    const cur = this.data.currentTab
    if (this.data.currentTabList.indexOf(cur) === -1) {
      this.onLoadmore()
    }
  },
  /** 活动详情 */
  todetail(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    wx.navigateTo({
      url: `/pages/activity/detail/detail?id=${id}`,
    })
  },
  /** 加入/取消加入 */
  async join(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item, index },
      },
    } = e
    if (this.data.wantJoin || item.wantJoin) {
      wx.showToast({
        title: '您已加入过了哟',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.setData({
      wantJoin: true,
    })
    await activityApi.wantJoinActivity(+item.id)
    const list = this.data.list
    list[this.data.currentTab][index].wantJoin = true
    this.setData({
      list,
      wantJoin: false,
    })
    wx.showToast({
      title: '加入成功',
      icon: 'none',
      duration: 1000,
    })
  },
  /** 获取分类列表 */
  async getClassify() {
    const recommend = {
      isLastPage: false,
      id: -1,
      name: '推荐',
    }
    const all = {
      isLastPage: false,
      id: -2,
      name: '全部',
    }
    let navData: any[] = []
    navData.push(recommend)
    navData.push(all)
    const netData = (await activityApi.getActivityClassify()).data
    navData = navData.concat(netData)
    navData.map((item) => (item.isLastPage = false))
    this.setData({
      navData,
    })
  },
  onPullDownRefresh() {
    this.onReset(false)
  },
  /** 刷新列表(第一次获取和刷新) */
  onReset(showLoadMore = true) {
    const navData = this.data.navData
    const list = [] as any[]
    const currentTabList = [] as number[]
    navData.map((item) => (item.isLastPage = false))
    this.setData({
      navData,
      list,
      currentTabList,
    })
    this.onLoadmore(showLoadMore)
  },
  /** 分页加载更多 */
  onReachBottom() {
    this.onLoadmore()
  },
  /**获取列表 */
  async onLoadmore(showLoadMore = true) {
    if (this.data.navData[this.data.currentTab].isLastPage) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }

    const currentTab = this.data.currentTab
    if (showLoadMore) {
      wx.showLoading({
        title: '加载中',
      })
    }
    // const page = pages ? pages : this.data.navData[currentTab].page
    const offset = this.data.list[currentTab] ? this.data.list[currentTab].length : ''
    const list =
      this.data.navData[currentTab].id === -1
        ? // 推荐
        await activityApi.getActivityList({
          recommended: 1,
          area: this.data.city && this.data.city != '全国' ? this.data.city : '',
          offset,
          limit: 20,
        })
        : this.data.navData[currentTab].id === -2
          ? // 全部
          await activityApi.getActivityList({
            area: this.data.city && this.data.city != '全国' ? this.data.city : '',
            offset,
            limit: 20,
          })
          : await activityApi.getActivityList({
            c: this.data.navData[currentTab].id,
            area: this.data.city && this.data.city != '全国' ? this.data.city : '',
            offset,
            limit: 20,
          })

    const isLastPage = list.length < 20
    const currentTabList = this.data.currentTabList
    currentTabList.indexOf(this.data.currentTab) == -1
      ? currentTabList.push(this.data.currentTab)
      : ''
    this.setData({
      [`list[${currentTab}]`]: this.data.list[currentTab]
        ? [...this.data.list[currentTab], ...list]
        : list,
      [`navData[${currentTab}].isLastPage`]: isLastPage,
      currentTabList,
    })
    wx.stopPullDownRefresh()
    wx.hideLoading()
  },
  /**创建活动 */
  toCreat() {
    wx.navigateTo({
      url: '/pages/activity/publish/publish?type=0',
    })
  },
  /** 选择活动定位 */
  chooseLocation() {
    wx.navigateTo({
      url: '/pages/activity/chooseCity/chooseCity',
    })
  },
  /** 搜索活动 */
  toSearch() {
    wx.navigateTo({
      url: '/pages/activity/search/search',
    })
  },
})
